import { Local } from "@/entity/helper/storage.helper";
import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import Food from "@/entity/interface/food.interfac";
import Config from "@/config";

export const useCommonStore = defineStore("Common", () => {
  const routerData = ref<any>(null);
  const routerStack = reactive(new Map());
  const productionEnv = ref<boolean>(false);
  const requestHeader = reactive<{ [x: string]: string }>(Local.get("requestHeader") || {});
  const getRequestHeader = () => requestHeader;
  const setRequestHeaderToken = (value: string) => {
    requestHeader["Authorization"] = value;
    Local.set("requestHeader", requestHeader);
  };
  const tabbarIndex = ref(Local.get("tabbarIndex") || 1);
  const getTabbarIndex = () => tabbarIndex.value;
  const setTabbarIndex = (value: number) => {
    tabbarIndex.value = value;
    Local.set("tabbarIndex", tabbarIndex.value);
  };
  const shopCar = reactive<{ [x: number]: Food }>(Local.get("shopCar") || {});
  const getShopCar = () => shopCar;
  const setShopCar = (key: number, value: Food) => {
    if (value.count === 0) Reflect.deleteProperty(shopCar, key);
    shopCar[key] = value;
    uni.$emit(Config.Event.setShopCar);
    uni.$emit(Config.Event.setShopCar + shopCar[key].id);
    Local.set("shopCar", shopCar);
  };
  const getShopCarList = () => {
    let result: Food[] = [];
    for (const key in shopCar) {
      if ((shopCar[key].count as number) > 0) result.push(shopCar[key]);
    }
    return result;
  };
  const getShopCarTotalPrice = () => {
    let sum = 0;
    for (const key in shopCar) {
      sum += (shopCar[key].count as number) * shopCar[key].singlePrice;
    }
    return sum;
  };

  return {
    routerData,
    routerStack,
    productionEnv,
    getRequestHeader,
    setRequestHeaderToken,
    getTabbarIndex,
    setTabbarIndex,
    setShopCar,
    getShopCar,
    getShopCarList,
    getShopCarTotalPrice,
  };
});
